package top.fullj.remoting.codec;

import com.caucho.hessian.io.Hessian2Output;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import top.fullj.remoting.message.Message;

import java.util.List;

/**
 * encode from Message to ByteBuf with hessian
 *
 * @author bruce.wu
 * @since 2022/2/15 16:32
 */
public class Hassian2Encoder extends MessageToMessageEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, List<Object> out) throws Exception {
        ByteBuf buf = ctx.alloc().buffer();
        ByteBufOutputStream os = new ByteBufOutputStream(buf);
        Hessian2Output output = new Hessian2Output(os);
        output.writeObject(msg);
        output.close();
        out.add(buf);
    }
}
